<template>
  <div style="border: 1px solid #EEEFF0;border-radius: 5px;overflow: hidden;width: 100%;">
    <Toolbar
      style="border-bottom: 1px solid #EEEFF0"
      :editor="editorRef"
      :defaultConfig="toolbarConfig"
      :mode="mode"
    />
    <Editor
      :style="{height: props.height}"
      v-model="valueHtml"
      :defaultConfig="editorConfig"
      :mode="mode"
      @onCreated="handleCreated"
    />
  </div>
</template>
  
  <script setup lang="ts">
import { Editor, Toolbar } from '@wangeditor/editor-for-vue';
import {
  ref,
  shallowRef,
  nextTick,
  computed,
  watch,
  onBeforeUnmount,
} from 'vue';
import { IToolbarConfig, DomEditor } from '@wangeditor/editor';
import { uploadFile } from '@/api/common';

// 配置
const toolbarConfig: Partial<IToolbarConfig> = {
  toolbarKeys: [
    'headerSelect',
    'bold',
    'italic',
    'underline',
    'through',
    'bulletedList',
    'justifyLeft',
    'justifyCenter',
    'justifyRight',
    'undo',
    'redo',
    'uploadImage',
    'insertLink',
  ],
  excludeKeys: ['group-video', 'divider', 'emotion', 'fullScreen'],
};

// 富文本 DOM 元素
const editorRef = shallowRef();

// "default" | "simple"; // 富文本模式 ==> 非必传（默认为 default）
const mode = 'default';

// 富文本的内容监听，触发父组件改变，实现双向数据绑定
interface Props {
    modelValue: string
    height?: number | string // 编辑器的高度
}
interface EmitEvent {
    (e: 'update:modelValue', params: string): void
}
const props = withDefaults(defineProps<Props>(), {
    height: '500px'
})
const emit = defineEmits<EmitEvent>()
const valueHtml = computed({
    get() {
        return props.modelValue
    },
    set(value: string) {
        emit('update:modelValue', value)
    }
})

// 编辑器组件
const editorConfig = {
  MENU_CONF: {
    uploadImage: {
      // 自定义图片上传
      async customUpload(file: any, insertFn: any) {
        uploadFile(file,{}).then((res) => {
          const url = res.data?.fileUrl; 
          insertFn(url);
        });
      },
    },
    uploadVideo: {
      // 自定义视频上传
      async customUpload(file: any, insertFn: any) {
        uploadFile(file,{}).then((res) => {
          const url = res.data?.fileUrl; 
          insertFn(url);
        });
      },
    },
  },
};

// 实例化编辑器
const handleCreated = (editor: any) => {
  editorRef.value = editor;
  nextTick(() => {
    // const toolbar = DomEditor.getToolbar(editor);
    // const curToolbarConfig = toolbar?.getConfig().toolbarKeys;
    // console.log('curToolbarConfig---', curToolbarConfig);
  });
};

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});

// 监听数据
watch(
    valueHtml,
  (newValue, oldValue) => {
  },
  { deep: true }
);
</script>
<style src="@wangeditor/editor/dist/css/style.css"></style>